//
//  YDPeripheralDetailViewController.m
//  IngCard
//
//  Created by kf on 2017/5/31.
//  Copyright © 2017年 IngDan. All rights reserved.
//

#import "YDPeripheralDetailViewController.h"
#import "BabyBluetooth.h"
#import "YDPeripheral.h"
#import "YDCustomToastContentView.h"
#import "YDCustomToastAnimator.h"
//#import "PeripheralInfo.h"
#import "YDPeripheralDetailTableViewCell.h"
#import "YDCharacteristicViewController.h"

#define channelOnPeropheralView @"peripheralDetailView"

@interface YDPeripheralDetailViewController ()
@property(nonatomic, strong) BabyBluetooth *baby;

@property(nonatomic, strong) QMUITips *tips;
//@property(nonatomic, strong) NSMutableArray<PeripheralInfo *> *services;
@end

@implementation YDPeripheralDetailViewController


-(void) initDataSource
{
    [super initDataSource];
    
    [self initBabyDelegate];
    
    
    self.baby.having(self.peripheral.peripheral).and.channel(channelOnPeropheralView).then.
    connectToPeripherals().//连接
    discoverServices().//查找协议
    discoverCharacteristics().//查找协议字段
    begin();
    
    self.tips = [QMUITips showLoading:NSStringFormat(@"开始连接设备：%@",self.peripheral.name)
                   inView:self.navigationController.view
           hideAfterDelay:1];
}
#pragma mark - <UITableViewDelegate>、<UITableViewDataSource>
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YDCharacteristicViewController *characteristicViewController = [[YDCharacteristicViewController alloc] init];
    characteristicViewController.peripheral = self.peripheral;
    YDPeripheralDetailTableViewCellModel* temp = [self.dataSource dataSourceAtIndexPath:indexPath];
    characteristicViewController.chararcterstic = temp.characteristic;
    [self.navigationController pushViewController:characteristicViewController animated:YES];
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    QMUILabel *label = [[QMUILabel alloc] init];
    CBService *service = [self.peripheral.peripheral.services objectAtIndex:section];
    label.text = [NSString stringWithFormat:@"协议：%@", service.UUID];
    label.font = UIFontMake(15);
    label.textColor = UIColorWhite;
    label.contentEdgeInsets = UIEdgeInsetsMake(4, 16, 4, 16);
    [label sizeToFit];
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0f;
}


#pragma mark - private 

-(void) initBabyDelegate
{
    __weak typeof(self)weakSelf = self;
    
    //设置设备连接成功的委托,同一个baby对象，使用不同的channel切换委托回调
    [self.baby setBlockOnConnectedAtChannel:channelOnPeropheralView
                                      block:^(CBCentralManager *central, CBPeripheral *peripheral)
    {
        __strong __typeof(weakSelf)self = weakSelf;
        
        [self.tips hideAnimated:NO];
        self.tips = [QMUITips showSucceed:NSStringFormat(@"连接%@成功",self.peripheral.name)
                       inView:self.navigationController.view
               hideAfterDelay:2];
    }];
    
    //设置设备连接失败的委托
    [self.baby setBlockOnFailToConnectAtChannel:channelOnPeropheralView
                                          block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error)
    {
        __strong __typeof(weakSelf)self = weakSelf;
        [self.tips hideAnimated:NO];
        self.tips = [QMUITips showSucceed:NSStringFormat(@"连接%@失败",self.peripheral.name)
                       inView:self.navigationController.view
               hideAfterDelay:2];
    }];
    
    //设置设备断开连接的委托
    [self.baby setBlockOnDisconnectAtChannel:channelOnPeropheralView
                                       block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error)
    {
        
    }];
    
    //设置发现设备的Services的委托
    [self.baby setBlockOnDiscoverServicesAtChannel:channelOnPeropheralView
                                             block:^(CBPeripheral *peripheral, NSError *error)
    {
        __strong __typeof(weakSelf)self = weakSelf;
        for (CBService *s in self.peripheral.peripheral.services) {
            
            Log(@"service UUID:%@",s.UUID);
        }
    }];
    //设置发现设service的Characteristics的委托
    [self.baby setBlockOnDiscoverCharacteristicsAtChannel:channelOnPeropheralView
                                                    block:^(CBPeripheral *peripheral, CBService *service, NSError *error)
     {
         __strong __typeof(weakSelf)self = weakSelf;
         NSInteger sectionIndex = [self.peripheral.peripheral.services indexOfObject:service];
         
         if (sectionIndex >= 0)
         {
             for (CBCharacteristic *characteristic in service.characteristics)
             {
                 [self.dataSource addDataSource:[YDPeripheralDetailTableViewCellModel class]
                                         atSection:sectionIndex
                                         config:^(YDPeripheralDetailTableViewCellModel* dataSource) {
                     dataSource.characteristic = characteristic;
                 }];
             }
         }
    }];
}

#pragma mark - lazy load

-(BabyBluetooth *) baby
{
    return [BabyBluetooth shareBabyBluetooth];
//    if (!_baby)
//    {
//        _baby = [BabyBluetooth shareBabyBluetooth];
//        
//        //扫描选项->CBCentralManagerScanOptionAllowDuplicatesKey:忽略同一个Peripheral端的多个发现事件被聚合成一个发现事件
//        NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
//        /*连接选项->
//         CBConnectPeripheralOptionNotifyOnConnectionKey :当应用挂起时，如果有一个连接成功时，如果我们想要系统为指定的peripheral显示一个提示时，就使用这个key值。
//         CBConnectPeripheralOptionNotifyOnDisconnectionKey :当应用挂起时，如果连接断开时，如果我们想要系统为指定的peripheral显示一个断开连接的提示时，就使用这个key值。
//         CBConnectPeripheralOptionNotifyOnNotificationKey: 当应用挂起时，使用该key值表示只要接收到给定peripheral端的通知就显示一个提
//         */
//        NSDictionary *connectOptions = @{CBConnectPeripheralOptionNotifyOnConnectionKey:@YES,
//                                         CBConnectPeripheralOptionNotifyOnDisconnectionKey:@YES,
//                                         CBConnectPeripheralOptionNotifyOnNotificationKey:@YES};
//        
//        [_baby setBabyOptionsAtChannel:channelOnPeropheralView
//        scanForPeripheralsWithOptions:scanForPeripheralsWithOptions
//          connectPeripheralWithOptions:connectOptions
//       scanForPeripheralsWithServices:nil
//                 discoverWithServices:nil
//          discoverWithCharacteristics:nil];
//    }
//    return _baby;
}

@end
